/*
 * Copyright 2010 J Patrick Davenport
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package v4view.core.utils;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

/**
 * Provides a common means by which binding can occur in the various components that seek to offer
 * such capacity. 
 * @author J Patrick Davenport
 *
 */
public class SimpleBinder {
	private static final String	SPLIT		= "+";
	private static final String	REGEX_SPLIT	= "\\+";
	private static final String	SPACE		= " ";
	private static final String	EMPTY		= "";

	public String bind(final Object o, final String bindingMethod) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		int countMatches = StringUtils.countMatches(bindingMethod, SPLIT);
		countMatches = countMatches + 1;
		final String[] split = bindingMethod.split(REGEX_SPLIT);
		final StringBuilder sb = new StringBuilder(EMPTY);
		for (int i = 0; i < countMatches; i++) {
			final String method = split[i];
			final Object result = PropertyUtils.getProperty(o, method.trim());
			final String stringResult = result == null ? EMPTY : result.toString();
			sb.append(stringResult);
			if ((i + 1) != countMatches) {
				sb.append(SPACE);
			}
		}
		return sb.toString();
	}
}